#!/usr/bin/env python3
"""
添加通知相关字段到tasks表的迁移脚本
"""
import sys
import os

# 添加项目根目录到路径
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))

from services.web.app import create_app
from services.shared.models import db

def migrate_notification_fields():
    """添加通知相关字段到tasks表"""
    app = create_app()
    
    with app.app_context():
        try:
            # 检查notify_on_failure字段是否已存在
            result = db.engine.execute("SHOW COLUMNS FROM tasks LIKE 'notify_on_failure'")
            if result.fetchone() is None:
                # 添加notify_on_failure字段
                db.engine.execute('ALTER TABLE tasks ADD COLUMN notify_on_failure BOOLEAN DEFAULT FALSE')
                print('已添加notify_on_failure字段')
            else:
                print('notify_on_failure字段已存在')
            
            # 检查notification_config_id字段是否已存在
            result = db.engine.execute("SHOW COLUMNS FROM tasks LIKE 'notification_config_id'")
            if result.fetchone() is None:
                # 添加notification_config_id字段
                db.engine.execute('ALTER TABLE tasks ADD COLUMN notification_config_id INT DEFAULT NULL')
                print('已添加notification_config_id字段')
            else:
                print('notification_config_id字段已存在')
            
            print('数据库迁移完成')
            
        except Exception as e:
            print(f'迁移失败: {str(e)}')
            return False
    
    return True

if __name__ == '__main__':
    migrate_notification_fields()